package com.vibrationkeyboard.app

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.vibrationkeyboard.app.databinding.ActivityMainBinding
import com.vibrationkeyboard.app.service.SensorDataService
import com.vibrationkeyboard.app.ui.SettingsActivity
import com.vibrationkeyboard.app.ui.VirtualKeyboardActivity
import com.vibrationkeyboard.app.viewmodel.MainViewModel

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: MainViewModel

    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.entries.all { it.value }
        if (allGranted) {
            startSensorService()
        } else {
            Toast.makeText(this, "需要传感器权限才能运行", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        
        setupUI()
        setupObservers()
        checkPermissions()
    }

    private fun setupUI() {
        binding.btnStartSensor.setOnClickListener {
            if (checkPermissions()) {
                startSensorService()
            }
        }

        binding.btnStopSensor.setOnClickListener {
            stopSensorService()
        }

        binding.btnOpenKeyboard.setOnClickListener {
            val intent = Intent(this, VirtualKeyboardActivity::class.java)
            startActivity(intent)
        }

        binding.btnSettings.setOnClickListener {
            val intent = Intent(this, SettingsActivity::class.java)
            startActivity(intent)
        }
    }

    private fun setupObservers() {
        viewModel.sensorStatus.observe(this) { status ->
            updateStatusIndicator(status)
        }

        viewModel.accelerometerData.observe(this) { data ->
            binding.tvAccX.text = "X: %.2f".format(data.x)
            binding.tvAccY.text = "Y: %.2f".format(data.y)
            binding.tvAccZ.text = "Z: %.2f".format(data.z)
        }

        viewModel.gyroscopeData.observe(this) { data ->
            binding.tvGyroX.text = "X: %.2f".format(data.x)
            binding.tvGyroY.text = "Y: %.2f".format(data.y)
            binding.tvGyroZ.text = "Z: %.2f".format(data.z)
        }

        viewModel.recognitionResult.observe(this) { result ->
            binding.tvRecognitionResult.text = result
        }
    }

    private fun checkPermissions(): Boolean {
        val permissions = arrayOf(
            Manifest.permission.BODY_SENSORS,
            Manifest.permission.BODY_SENSORS_BACKGROUND
        )

        val permissionsToRequest = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }.toTypedArray()

        if (permissionsToRequest.isNotEmpty()) {
            requestPermissionLauncher.launch(permissionsToRequest)
            return false
        }
        return true
    }

    private fun startSensorService() {
        val intent = Intent(this, SensorDataService::class.java)
        startForegroundService(intent)
        viewModel.setSensorStatus(SensorStatus.RUNNING)
        Toast.makeText(this, "传感器服务已启动", Toast.LENGTH_SHORT).show()
    }

    private fun stopSensorService() {
        val intent = Intent(this, SensorDataService::class.java)
        stopService(intent)
        viewModel.setSensorStatus(SensorStatus.STOPPED)
        Toast.makeText(this, "传感器服务已停止", Toast.LENGTH_SHORT).show()
    }

    private fun updateStatusIndicator(status: SensorStatus) {
        val (indicatorRes, statusText) = when (status) {
            SensorStatus.RUNNING -> {
                binding.vStatusIndicator.setBackgroundResource(R.drawable.status_indicator_connected)
                getString(R.string.sensor_status_running)
            }
            SensorStatus.STOPPED -> {
                binding.vStatusIndicator.setBackgroundResource(R.drawable.status_indicator_disconnected)
                getString(R.string.sensor_status_stopped)
            }
            SensorStatus.ERROR -> {
                binding.vStatusIndicator.setBackgroundResource(R.drawable.status_indicator_processing)
                getString(R.string.sensor_status_error)
            }
        }
        binding.tvStatusText.text = statusText
    }

    override fun onDestroy() {
        super.onDestroy()
        stopSensorService()
    }
}

enum class SensorStatus {
    RUNNING, STOPPED, ERROR
} 